//
//  HPYComposeViewController.swift
//  SwiftVVBo
//
//  Created by hepeiyong on 16/8/18.
//  Copyright © 2016年 hpyhn. All rights reserved.
//

import UIKit
import SVProgressHUD

class HPYComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }

    // MARK: - 监听事件
    @objc private func cancelAction(){
        // 取消键盘第一响应
        composeTextView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }

    @objc private func sendAction(){
        print("发布按钮点击")

        //        if composePictureView.imageList.count == 0 {
        //            update()
        //        }else {
        //            upload()
        //        }
        composePictureView.imageList.count == 0 ? update() : upload()
    }


    // MARK: - 设置视图
    private func setupUI(){
        view.backgroundColor = UIColor.whiteColor()
        setupNav()
        // 添加控件
        view.addSubview(composeTextView)
        view.addSubview(composeBottomView)
        composeTextView.addSubview(composePictureView)
        // 添加约束
        composeTextView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }

        composeBottomView.snp_makeConstraints { (make) -> Void in
            make.leading.bottom.trailing.equalTo(view)
            make.height.equalTo(44)
        }

        composePictureView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(composeTextView).offset(100)
            make.size.equalTo(CGSize(width: SCREENW - 20, height: SCREENW - 20))
            make.centerX.equalTo(composeTextView)
        }

        //  监听底部view 中按钮点击回调 02
        composeBottomView.closure = {[weak self] (type: HPYComposeBottomViewType)->() in
            // 04
            switch type{
            case .Picture:
                print("图片")
                self?.selectImages()
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emoticon:
                print("笑脸")
                self?.switchKeyboard()
            case .Add:
                print("+")
            }
        }
        // 02配图闭包回调 选择图片
        composePictureView.closure = { [weak self] in
            // 04
            self?.selectImages()
        }

        // 注册通知 监听键盘将要改变frame'
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HPYComposeViewController.keyboardWillChangeFrame(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)


    }
    // 监听键盘frame 改变
    func keyboardWillChangeFrame(noti: NSNotification){
        // 动画时长
        guard let duration = noti.userInfo?["UIKeyboardAnimationDurationUserInfoKey"] as? Double else{
            return
        }
        // 判断他是否为nil 而且是否可以转成NSValue
        guard let rect = noti.userInfo?["UIKeyboardFrameEndUserInfoKey"] as? NSValue else{
            return
        }
        // 获取到CGRect
        let newRect = rect.CGRectValue()
        //newRect.origin.y
        // 更新约束
        composeBottomView.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(newRect.origin.y - SCREENH)
        }

        // 设置动画
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }


    // MARK: - 设置导航
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(HPYComposeViewController.cancelAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(HPYComposeViewController.sendAction))
        // 设置不能点击 ()
        navigationItem.rightBarButtonItem?.enabled = false
        navigationItem.titleView = titleView
    }

    // MARK: - 懒加载控件
    private lazy var titleView: UILabel = {
        // 用户昵称
        let name = HPYUserAccountViewModel.sharedTools.userAccount!.screen_name!
        // 显示内容
        let str = "发微博\n\(name)"
        // 获取范围
        let range = (str as NSString).rangeOfString(name)
        // 初始化一个富文本
        let attr = NSMutableAttributedString(string: str)
        // 设置富文本
        attr.addAttributes([NSForegroundColorAttributeName: AppThemeColor, NSFontAttributeName: UIFont.systemFontOfSize(12)], range: range)
        let lab = UILabel()
        lab.numberOfLines = 0
        lab.textAlignment = .Center
        lab.attributedText = attr
        lab.sizeToFit()
        return lab
    }()
    // 自定义textView
    private lazy var composeTextView: HPYComposeTextView = {
        let view = HPYComposeTextView()
        view.delegate = self
        // 设置字体
        view.font = UIFont.systemFontOfSize(16)
        // 设置占位文字
        view.placeholder = "在这里可以分享你的精彩生活..."
        // 允许上下移动
        view.alwaysBounceVertical = true
        return view
    }()
    // 自定义底部视图
    private lazy var composeBottomView: HPYComposeBottomView = HPYComposeBottomView()
    // 配图
    private lazy var composePictureView: HPYComposePictureView = HPYComposePictureView()
    // 自定义表情键盘
    @available(iOS 9.0, *)
    private lazy var emoticonKeyboardView: HPYEmoticonKeyboardView = HPYEmoticonKeyboardView(frame: CGRect(x: 0, y: 0, width: SCREENW, height: 216))


    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

}

extension HPYComposeViewController {
    // 发布文字微博
    func update(){
        HPYNetworkTools.sharedTools.composeUpdate(composeTextView.text, success: { (response) -> () in
            SVProgressHUD.showSuccessWithStatus("发布成功")
            //MARK: -- 发布通知
            NSNotificationCenter.defaultCenter().postNotificationName("refreshDate", object: nil)
            self.cancelAction()
        }) { (error) -> () in
            SVProgressHUD.showErrorWithStatus("发布失败")
        }
    }

    // 发布图片微博
    func upload(){
        HPYNetworkTools.sharedTools.composeUpload(composeTextView.text, images: composePictureView.imageList, success: { (response) -> () in
            SVProgressHUD.showSuccessWithStatus("发布成功")
            //MARK: --发送通知
            NSNotificationCenter.defaultCenter().postNotificationName("refreshDate", object: nil)
            self.cancelAction()
        }) { (error) -> () in
            SVProgressHUD.showErrorWithStatus("发布失败")
        }
    }

}

// MARK: - 处理ComposeBottomView按钮的事件
extension HPYComposeViewController{
    // 选择图片
    func selectImages(){
        let pickerVc = UIImagePickerController()
        // 设置代理
        pickerVc.delegate = self
        self.presentViewController(pickerVc, animated: true, completion: nil)
    }
    // 切换键盘
    func switchKeyboard(){
        // 代表显示的为系统键盘
        if composeTextView.inputView == nil {
            if #available(iOS 9.0, *) {
                composeTextView.inputView = emoticonKeyboardView
            } else {
                // Fallback on earlier versions
            }
            //
            composeBottomView.isEmoticon = true
        }else {
            // 代表显示的为自定义表情键盘
            composeTextView.inputView = nil
            composeBottomView.isEmoticon = false
        }
        // 刷新
        composeTextView.reloadInputViews()
        // 成为第一响应者
        composeTextView.becomeFirstResponder()
    }
}

extension HPYComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
        func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        let image = info["UIImagePickerControllerOriginalImage"] as! UIImage
              // 添加图片
        composePictureView.addImages(UIImage.dealImageScale(image, width: 600))
        // 关闭控制器
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    /*
     - 用户上传头像 需要先压缩 然后上传
     - 服务器端得到后 它会通过他的渲染方式 保存一张上传的 和一张高清的 然后在你需要对应的图片的时候 给你提供对应的图片
     */
    // 图片压缩(等比例压缩)
    func dealImageScale(image: UIImage, width: CGFloat) -> UIImage{
        // 如果规定的宽度大于图片实际的宽度 直接返回
        if image.size.width < width {
            return image
        }
        /*
         1200     600
         800      x
         */
        // 等比例后的高度
        let height = image.size.height*width/image.size.width
        //  计算rect
        let rect = CGRect(x: 0, y: 0, width: width, height: height)
        // 01 开启上下文
        UIGraphicsBeginImageContext(rect.size)
        // 02 把内容渲染到上下文中
        image.drawInRect(rect)
        // 03 从上下文获取内容
        let result = UIGraphicsGetImageFromCurrentImageContext()
        // 04 关闭上下文
        UIGraphicsEndImageContext()
        return result
    }

    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        print("取消啦")
        // 关闭控制器
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}

// MARK: - UITextViewDelegate
extension HPYComposeViewController: UITextViewDelegate{
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }

    func scrollViewDidScroll(scrollView: UIScrollView) {
        // 取消键盘第一响应
        self.composeTextView.resignFirstResponder()
    }
}
